//
//  TestSelectViewController.m
//  AndCampus
//
//  Created by 史宵宵 on 2018/3/28.
//  Copyright © 2018年 史宵宵. All rights reserved.
//

#import "TestSelectViewController.h"
#import "TestSelectTableViewCell.h"
#import "RIASECTableViewCell.h"
#import "PictureTestTableViewCell.h"
#import "ResultTestViewController.h"
#import "ResultCircularViewController.h"
#import "PayActivityInforViewController.h"

@interface TestSelectViewController ()
@property (nonatomic,strong) NSMutableArray *dataArray;
@property (nonatomic,assign) NSInteger currentIndex;
@property (nonatomic,assign) BOOL isPay;
@end

@implementation TestSelectViewController
- (NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"专业测评";
//    UIImageView *imageView=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0,kScreenW, kScreenH)];
//    imageView.image=[UIImage imageNamed:@"Testlist_bg"];
//    self.tableView.backgroundView = imageView;
    UIImage *image = [UIImage imageNamed:@"Testlist_bg"];
    self.view.layer.contents = (id) image.CGImage;
    self.tableView.frame = CGRectMake(0, 100, kScreenW, kScreenH - 80 - 69- 100);
    self.tableView.backgroundColor = [UIColor clearColor];
    
    self.currentIndex = 0;
    [self creatDataList];
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([TestSelectTableViewCell class]) bundle:nil] forCellReuseIdentifier:@"TestSelectTableViewCell"];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([RIASECTableViewCell class]) bundle:nil] forCellReuseIdentifier:@"RIASECTableViewCell"];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([PictureTestTableViewCell class]) bundle:nil] forCellReuseIdentifier:@"PictureTestTableViewCell"];
    
    
//    UIView *headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenW, 90)];
//    headView.backgroundColor = [UIColor clearColor];
//    self.tableView.tableHeaderView = headView;
    
}
#pragma mark - 获取专业测试--------获取题库列表
- (void)creatDataList{
    YJNetWorkManger *yjNetWorkManger =  [YJNetWorkManger shareManager];
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
    [dic setValue:[Global getUserTokenInfo] forKey:@"token"];   //token
    [dic setValue:self.testType forKey:@"type"];   //1成人测试 2儿童测试 3职业测试 4智能测试 5 MBTI 职业性格测验
    
    [yjNetWorkManger requestType:POST andURL:[JSPathUtil urlAppInterestGetQuestions] andParmas:dic andComplition:^(id response, BOOL isuccess) {
        if (isuccess) {
            NSArray *array = [NSArray arrayWithArray:response[@"questionList"]];
            NSArray *arrayPicture = [NSArray arrayWithArray:response[@"questionList1"]];
            self.isPay = [[NSString stringWithFormat:@"%@",response[@"need_pay"]] isEqualToString:@"0"]?NO:YES;
            if (array.count || arrayPicture.count) {
                if ([self.testType isEqualToString:@"1"] || [self.testType isEqualToString:@"2"] ) {
                    [TestSelectModel mj_setupReplacedKeyFromPropertyName:^NSDictionary *{
                        return @{@"selectTestId" : @"id"};
                    }];
                    [self.dataArray addObjectsFromArray:[TestSelectModel mj_objectArrayWithKeyValuesArray:response[@"questionList"]]];
                }else if ([self.testType isEqualToString:@"3"]){
                    [ProfessionalTestModel mj_setupObjectClassInArray:^NSDictionary *{
                        return @{@"question":@"TestSelectModel"};
                    }];
                    [TestSelectModel mj_setupReplacedKeyFromPropertyName:^NSDictionary *{
                        return @{@"selectTestId" : @"id"};
                    }];
                    [self.dataArray addObjectsFromArray:[ProfessionalTestModel mj_objectArrayWithKeyValuesArray:response[@"questionList"]]];
                }else if ([self.testType isEqualToString:@"4"]){
                    [TestSelectModel mj_setupReplacedKeyFromPropertyName:^NSDictionary *{
                        return @{@"selectTestId" : @"id"};
                    }];
                    [self.dataArray addObjectsFromArray:[TestSelectModel mj_objectArrayWithKeyValuesArray:response[@"questionList1"]]];
                    [self.dataArray addObjectsFromArray:[PictureTestModel mj_objectArrayWithKeyValuesArray:response[@"image_title"]]];
                    [self.dataArray addObjectsFromArray:[TestSelectModel mj_objectArrayWithKeyValuesArray:response[@"questionList2"]]];
                }else{
                    [self.dataArray addObjectsFromArray:[TestSelectModel mj_objectArrayWithKeyValuesArray:response[@"questionList"]]];
                }
                [self.tableView reloadData];
            }
        }
    }];
}
#pragma mark - 专业测试--------提交答案
- (void)submit{
    
    if (self.currentIndex < self.dataArray.count-1) {
        [Global showActivityWithView:self.view withText:@"还没有答完题目"];
        return;
    }
    if (self.isPay) {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message: [NSString stringWithFormat:@"本测评量表目前针对个人是收费项目一次性收费80元"] preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
            
        }];
        UIAlertAction *otherAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            __weak typeof(self) unself=self;
            PayActivityInforViewController *payActivityInforVC = [[PayActivityInforViewController alloc]init];
            payActivityInforVC.modalPresentationStyle = UIModalPresentationOverCurrentContext;
            payActivityInforVC.moneyStr = @"0.01";
            payActivityInforVC.numId = self.testType;
            payActivityInforVC.titleStr = @"专业测评";
            payActivityInforVC.payType = @"test";
            payActivityInforVC.paySuccessBlack = ^{
                unself.isPay = NO;
                [unself submit];
            };
            UIViewController *appRootVC = [UIApplication sharedApplication].keyWindow.rootViewController;
            [appRootVC presentViewController:payActivityInforVC animated:YES completion:^{
                
            }];
        }];
        [alertController addAction:cancelAction];
        [alertController addAction:otherAction];
        [self presentViewController:alertController animated:YES completion:nil];
        
    }
    
    YJNetWorkManger *yjNetWorkManger =  [YJNetWorkManger shareManager];
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
    [dic setValue:[Global getUserTokenInfo] forKey:@"token"];   //token
    [dic setValue:self.testType forKey:@"type"];   //1成人测试 2儿童测试 3职业测试 4智能测试  5 MBTI 职业性格测验
    
    if ([self.testType isEqualToString:@"1"] || [self.testType isEqualToString:@"2"] || [self.testType isEqualToString:@"5"]) {
        TestSelectModel *textSelectInfo = self.dataArray[self.currentIndex];
        if (strIsEmpty(textSelectInfo.answer)) {
            [Global showActivityWithView:self.view withText:@"请选择答案"];
            return;
        }
        NSMutableString *answerStr = [[NSMutableString alloc]initWithString:@""];
        [self.dataArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            TestSelectModel *testSelectInfo = obj;
            [answerStr appendString:testSelectInfo.answer];
        }];
        [dic setValue:answerStr forKey:@"answer"];    //提交答案
    //    [dic setValue:@"0011100100111001100011100110001110011000111001100011100110001110011000111001100011100110" forKey:@"answer"];    //提交答案
    }else if ([self.testType isEqualToString:@"3"]){
        ProfessionalTestModel *professionalTestInfo = self.dataArray[self.currentIndex];
        if (strIsEmpty(professionalTestInfo.answer)) {
            [Global showActivityWithView:self.view withText:@"请选择答案"];
            return;
        }
        NSArray *scoreArray = [professionalTestInfo.answer componentsSeparatedByString:@","];
        int sum = [[scoreArray valueForKeyPath:@"@sum.intValue"] intValue];//求和
        if (sum != 25) {
            [Global showActivityWithView:self.view withText:@"必须25分"];
            return;
        }
        NSMutableString *answerStr = [[NSMutableString alloc]initWithString:@""];
        [self.dataArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            ProfessionalTestModel *professionalTestInfo = obj;
            if (idx) {
                 [answerStr appendString:[NSString stringWithFormat:@"-%@",professionalTestInfo.answer]];
            }else{
                 [answerStr appendString:[NSString stringWithFormat:@"%@",professionalTestInfo.answer]];
            }
           
        }];
        [dic setValue:answerStr forKey:@"answer"];    //提交答案
    }else if ([self.testType isEqualToString:@"4"]) {
        id textSelectInfo = self.dataArray[self.currentIndex];
        if ( TestSelectModel.class == [textSelectInfo class]) {
            TestSelectModel *testSelectInfo = self.dataArray[self.currentIndex];
            if (strIsEmpty(testSelectInfo.answer)) {
                [Global showActivityWithView:self.view withText:@"请选择答案"];
                return;
            }
        }else{
            PictureTestModel *pictureTestInfo = self.dataArray[self.currentIndex];
            if (strIsEmpty(pictureTestInfo.answer)) {
                [Global showActivityWithView:self.view withText:@"请选择答案"];
                return;
            }
        }
        NSMutableString *answerStr = [[NSMutableString alloc]initWithString:@""];
        [self.dataArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            id textSelectInfo = self.dataArray[self.currentIndex];
            if ( TestSelectModel.class == [textSelectInfo class]) {
                TestSelectModel *testSelectInfo = obj;
                [answerStr appendString:testSelectInfo.answer];
            }else{
                PictureTestModel *pictureTestInfo = obj;
                [answerStr appendString:pictureTestInfo.answer];
            }
        }];
        [dic setValue:answerStr forKey:@"answer"];    //提交答案
        
    }
    
    [yjNetWorkManger requestType:POST andURL:[JSPathUtil urlAppInterestAddAnswer] andParmas:dic andComplition:^(id response, BOOL isuccess) {
        if (isuccess) {
            
            if ([self.testType isEqualToString:@"1"] || [self.testType isEqualToString:@"2"] ) {
                NSString *answer_title = response[@"answer_title"];
                NSString *answer_content = response[@"answer_content"];
                ResultTestViewController *resultTestVC = [[ResultTestViewController alloc]init];
                resultTestVC.titleStr = answer_title;
                resultTestVC.content = answer_content;
                [self.navigationController pushViewController:resultTestVC animated:YES];
            }else if ([self.testType isEqualToString:@"3"]){
                ResultTestViewController *resultTestVC = [[ResultTestViewController alloc]init];
                resultTestVC.resultTypeStr = @"Description";
                resultTestVC.title = @"";
                NSArray *answerArray = [NSArray arrayWithArray:response[@"work_test_answer"]];
                NSString *answerStr = [answerArray componentsJoinedByString:@"\n" ];
                resultTestVC.content = answerStr;
                [self.navigationController pushViewController:resultTestVC animated:YES];
            }else if ([self.testType isEqualToString:@"4"]){
                ResultCircularViewController *resultCircularVC = [[ResultCircularViewController alloc]init];
                resultCircularVC.answerList = response[@"answerList"];
                resultCircularVC.perAnswerList = response[@"per_answer"];
                [self.navigationController pushViewController:resultCircularVC animated:YES];
            }if ([self.testType isEqualToString:@"5"] ) {
//                NSString *answer_title = response[@"MBTI_RESULT_TITLE"];
                NSString *answer_content = [NSString stringWithFormat:@"性格类型代码与简述:%@\n性格特征:%@\n较适合的职业:%@\n较适合专业:%@",response[@"MBTI_RESULT_TITLE"],response[@"MBTI_RESULT_ANSWER"],response[@"MBTI_RESULT_OCCU"],response[@"MBTI_RESULT_MAJOR"]];
                ResultTestViewController *resultTestVC = [[ResultTestViewController alloc]init];
                resultTestVC.titleStr = @"";
                resultTestVC.content = answer_content;
                [self.navigationController pushViewController:resultTestVC animated:YES];
            }
        }
    }];
}
- (NSInteger )numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count?1:self.dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([self.testType isEqualToString:@"1"] || [self.testType isEqualToString:@"2"] ) {
        TestSelectTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"TestSelectTableViewCell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.num = self.currentIndex+1;
        cell.total = self.dataArray.count;
        cell.testSelectType = KYESORNOTestSelectType;
        cell.testSelectInfo = self.dataArray[self.currentIndex];
        cell.backgroundColor = [UIColor clearColor];
        __weak typeof(self) unself = self;
        cell.selectTestBlock = ^(NSString *answer) {
            TestSelectModel *testSelectInfo = unself.dataArray[self.currentIndex];
            testSelectInfo.answer = answer;
            [unself.dataArray replaceObjectAtIndex:self.currentIndex withObject:testSelectInfo];
        };
        return cell;
    }else if([self.testType isEqualToString:@"3"]){
        RIASECTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"RIASECTableViewCell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.backgroundColor = [UIColor clearColor];
        cell.num = self.currentIndex+1;
        cell.total = self.dataArray.count;
        cell.professionalTestInfo = self.dataArray[self.currentIndex];
        __weak typeof(self) unself = self;
        cell.selectRIASECTestBlock = ^(NSString *answer) {
            ProfessionalTestModel *professionalTestInfo = unself.dataArray[self.currentIndex];
            professionalTestInfo.answer = answer;
            [unself.dataArray replaceObjectAtIndex:self.currentIndex withObject:professionalTestInfo];
        };
        return cell;
    }if ([self.testType isEqualToString:@"5"] ) {
        TestSelectTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"TestSelectTableViewCell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.num = self.currentIndex+1;
        cell.total = self.dataArray.count;
        cell.testSelectType = KMoreAnswerTestSelectType;
        cell.testSelectInfo = self.dataArray[self.currentIndex];
        cell.backgroundColor = [UIColor clearColor];
        __weak typeof(self) unself = self;
        cell.selectTestBlock = ^(NSString *answer) {
            TestSelectModel *testSelectInfo = unself.dataArray[self.currentIndex];
            testSelectInfo.answer = answer;
            [unself.dataArray replaceObjectAtIndex:self.currentIndex withObject:testSelectInfo];
        };
        return cell;
    }else{
        id pictureTestInfo = self.dataArray[self.currentIndex];
        
        if ( TestSelectModel.class == [pictureTestInfo class]) {
            TestSelectTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"TestSelectTableViewCell" forIndexPath:indexPath];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.num = self.currentIndex+1;
            cell.total = self.dataArray.count;
            cell.testSelectType = KYESORNOTestSelectType;
            cell.testSelectInfo = self.dataArray[self.currentIndex];
            cell.backgroundColor = [UIColor clearColor];
            __weak typeof(self) unself = self;
            cell.selectTestBlock = ^(NSString *answer) {
                TestSelectModel *testSelectInfo = unself.dataArray[self.currentIndex];
                testSelectInfo.answer = answer;
                [unself.dataArray replaceObjectAtIndex:self.currentIndex withObject:testSelectInfo];
            };
            return cell;
        }
        PictureTestTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"PictureTestTableViewCell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.num = self.currentIndex +1;
        cell.total = self.dataArray.count;
        cell.pictureTestInfo = self.dataArray[self.currentIndex];
        cell.backgroundColor = [UIColor clearColor];
        __weak typeof(self) unself = self;
        cell.selectPictureTestBlock = ^(NSString *answer) {
            PictureTestModel *pictureTestInfo = unself.dataArray[self.currentIndex];
            pictureTestInfo.answer = answer;
            [unself.dataArray replaceObjectAtIndex:self.currentIndex withObject:pictureTestInfo];
        };
        return cell;
    }
    
}

//-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//    if ([self.testType isEqualToString:@"1"] || [self.testType isEqualToString:@"2"] ) {
//        CGFloat cellheight=[tableView fd_heightForCellWithIdentifier:@"TestSelectTableViewCell" configuration:^(TestSelectTableViewCell *cell) {
//            cell.testSelectInfo = self.dataArray[self.currentIndex];
//        }];
//
//        return cellheight;
//
//    }else if ([self.testType isEqualToString:@"3"]){
//        return  [tableView fd_heightForCellWithIdentifier:@"RIASECTableViewCell" configuration:^(RIASECTableViewCell *cell) {
//            cell.professionalTestInfo = self.dataArray[self.currentIndex];
//        }];
//    }else{
//        id pictureTestInfo = self.dataArray[self.currentIndex];
//
//        if ( TestSelectModel.class == [pictureTestInfo class]) {
//            return  [tableView fd_heightForCellWithIdentifier:@"TestSelectTableViewCell" configuration:^(TestSelectTableViewCell *cell) {
//                cell.testSelectInfo = self.dataArray[self.currentIndex];
//            }];
//        }else{
//            return  [tableView fd_heightForCellWithIdentifier:@"PictureTestTableViewCell" configuration:^(PictureTestTableViewCell *cell) {
//                cell.pictureTestInfo = self.dataArray[self.currentIndex];
//            }];
//        }
//    }
//}
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 120;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewAutomaticDimension;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *footView = [[UIView alloc]init];
    footView.backgroundColor = [UIColor clearColor];
    footView.frame = CGRectMake( 0, 0, kScreenW, 100);
    
    UIButton *lastButton = [[UIButton alloc]initWithFrame:CGRectMake((kScreenW - 40)/2, 10, 40, 40)];
    [lastButton setImage:[UIImage imageNamed:@"translate_up"] forState:UIControlStateNormal];
    [lastButton addTarget:self action:@selector(lastQuestion) forControlEvents:UIControlEventTouchUpInside];
    [footView addSubview:lastButton];
    
    if (self.currentIndex == self.dataArray.count - 1) {
        CompleteButton *completeButton = [[CompleteButton alloc]initWithFrame:CGRectMake((kScreenW - 100)/2, 60, 100, 40) bgColor:KBACKNAVIGATIONCOLOR tColor:[UIColor whiteColor] text:@"提交"];
        [completeButton addTarget:self action:@selector(submit) forControlEvents:UIControlEventTouchUpInside];
        [footView addSubview:completeButton];
    }else{
        UIButton *nextButton = [[UIButton alloc]initWithFrame:CGRectMake((kScreenW - 40)/2, 60, 40, 40)];
        [nextButton setImage:[UIImage imageNamed:@"translate_down"] forState:UIControlStateNormal];
        [nextButton addTarget:self action:@selector(nextQuestion) forControlEvents:UIControlEventTouchUpInside];
        [footView addSubview:nextButton];
    }
    
    
    return footView;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 100;
}
#pragma mark - 上一题
- (void)lastQuestion{
    if (self.currentIndex < 1) {
        [Global showActivityWithView:self.view withText:@"已是第一题"];
        return;
    }
    self.currentIndex = self.currentIndex - 1;
    self.navigationItem.rightBarButtonItem = nil;
    [self.tableView reloadData];
}
#pragma mark - 下一题
- (void)nextQuestion{
    
    if (self.currentIndex == self.dataArray.count-1) {
        [Global showActivityWithView:self.view withText:@"已是最后一题"];
        return;
    }
    if ([self.testType isEqualToString:@"1"] || [self.testType isEqualToString:@"2"] || [self.testType isEqualToString:@"5"]) {
        TestSelectModel *textSelectInfo = self.dataArray[self.currentIndex];
        if (strIsEmpty(textSelectInfo.answer)) {
            [Global showActivityWithView:self.view withText:@"请选择答案"];
            return;
        }
    }else if([self.testType isEqualToString:@"3"]){
        ProfessionalTestModel *professionalTestInfo = self.dataArray[self.currentIndex];
        if (strIsEmpty(professionalTestInfo.answer)) {
            [Global showActivityWithView:self.view withText:@"请选择答案"];
            return;
        }
        NSArray *scoreArray = [professionalTestInfo.answer componentsSeparatedByString:@","];
        int sum = [[scoreArray valueForKeyPath:@"@sum.intValue"] intValue];//求和
        if (sum != 25) {
            [Global showActivityWithView:self.view withText:@"必须25分"];
            return;
        }
    }else if ([self.testType isEqualToString:@"4"]) {
        id textSelectInfo = self.dataArray[self.currentIndex];
        if ( TestSelectModel.class == [textSelectInfo class]) {
            TestSelectModel *testSelectInfo = self.dataArray[self.currentIndex];
            if (strIsEmpty(testSelectInfo.answer)) {
                [Global showActivityWithView:self.view withText:@"请选择答案"];
                return;
            }
        }else{
            PictureTestModel *pictureTestInfo = self.dataArray[self.currentIndex];
            if (strIsEmpty(pictureTestInfo.answer)) {
                [Global showActivityWithView:self.view withText:@"请选择答案"];
                return;
            }
        }
        
    }
    
    self.currentIndex = self.currentIndex + 1;
//    if (self.currentIndex == self.dataArray.count - 1) {
//        self.navigationItem.rightBarButtonItem = [UIBarButtonItem rightBarButtonItemWithTitle:@"提交" target:self selector:@selector(submit)];
//    }else{
//        self.navigationItem.rightBarButtonItem = nil;
//    }
//    self.tableView.scroll.contentOffset = CGPointMake(0, 0);
    [self.tableView reloadData];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
